package com.milk.milkpush;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Collection;
import java.util.Date;

@RequestMapping("polling")
@CrossOrigin
@Controller
public class PollingController {

    @GetMapping(value = "short/index")
    public String shortIndex() {
        System.out.println("index");
        return "short-poll";
    }

    @GetMapping(value = "long/index")
    public String longIndex() {
        System.out.println("index");
        return "long-poll";
    }

    /**************************************************************短轮训******************************************************************************************/


    /**
     * 短轮训接口
     *
     * @return {@code String}
     */
    @GetMapping(value = "poll")
    @ResponseBody
    public String poll() {
        return "Hello";
    }

    /**************************************************************长轮训******************************************************************************************/

    private static final Long TIME_OUT = 5000L;


    // 存放监听某个Id的长轮询集合
    // 线程同步结构
    public static Multimap<String, DeferredResult<String>> watchRequests = Multimaps.synchronizedMultimap(HashMultimap.create());

    /**
     * 程序员小富
     * 设置监听
     */
    @GetMapping(path = "watch/{id}")
    @ResponseBody
    public DeferredResult<String> watch(@PathVariable String id) {
        // 延迟对象设置超时时间
        DeferredResult<String> deferredResult = new DeferredResult<>(TIME_OUT);
        // 异步请求完成时移除 key，防止内存溢出
        deferredResult.onCompletion(() -> {
            watchRequests.remove(id, deferredResult);
        });
        // 注册长轮询请求
        watchRequests.put(id, deferredResult);
        // note:其实是卡在这了,deferred本身有一个超时时间，会等待result,而下面的publish接口setResult之后这边就会返回
        return deferredResult;
    }

    /**
     * 程序员小富
     * 变更数据
     */
    @GetMapping(path = "publish/{id}")
    @ResponseBody
    public String publish(@PathVariable String id) {
        // 数据变更 取出监听ID的所有长轮询请求，并一一响应处理
        if (watchRequests.containsKey(id)) {
            Collection<DeferredResult<String>> deferredResults = watchRequests.get(id);
            for (DeferredResult<String> deferredResult : deferredResults) {
                deferredResult.setResult("我更新了" + new Date());
            }
        }
        return "success";
    }

//    @GetMapping(path = "message")
//    public void message(HttpServletResponse response) throws IOException, InterruptedException {
//        while (true) {
//            response.setHeader("Pragma", "no-cache");
//            response.setDateHeader("Expires", 0);
//            response.setHeader("Cache-Control", "no-cache,no-store");
//            response.setStatus(HttpServletResponse.SC_OK);
//            response.getWriter().print(" <script type=\"text/javascript\">\n" +
//                    "parent.document.getElementById('clock').innerHTML = \"" + count.get() + "\";" +
//                    "parent.document.getElementById('count').innerHTML = \"" + count.get() + "\";" +
//                    "</script>");
//        }
//    }
}
